<?php
/**
 * Created by jinqiang on 2024/7/8 10:19.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\SsyAdditionalAmountTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderReturnTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use App\Http\Models\Mysql\SsyFineAmountTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyPurchaseReturnTable;
use App\Http\Models\Mysql\SsyPushKingdeeLogTable;
use App\Http\Models\Mysql\SsyReconciliationOrderTable;
use App\Http\Models\Mysql\SsyReconciliationOrderZgTable;
use App\Http\Models\Mysql\SsyRepairAmountTable;
use App\Http\Models\Mysql\SsyRepairReconciliationOrderTable;

class KingdeeRepository
{
    //推送--调拨借
    public static function pushAllocationJ($allocationObj, $sub)
    {
        //杭州次品仓 调拨单据
        $allocationNumberCPList = WmsRepository::ALLOCATION_CP_NUMBER;
        $orgNo = ['mz' => '100', 'kz' => '100'];//调入调出库存组织编码
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationObj['allocation_number'])
            ->get(['sku_code as material_no', 'num as qty'])->toArray();
        foreach ($allocationOrders as &$item){
            $item['instockno'] = 'DBJ';
            $item['outstockno'] = in_array($allocationObj['allocation_number'], $allocationNumberCPList)? 'HZCPC' : 'HZC';
        }
        unset($item);
        $data = [
            "billtype" => 'ZJDB01_SYS',
            "transferdirecttype" => "InnerOrgTransfer",
            "outstockorgno" => $orgNo[$sub],
            "outownerno" => $orgNo[$sub],
            "instockorgno" => $orgNo[$sub],
            "inownerno" => $orgNo[$sub],
            "details" => $allocationOrders,
            "id" => 0,
            "billNo" => $allocationObj['allocation_number'],
            "date" => $allocationObj['createtime'],
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            "headers" =>["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url="http://139.224.58.121/kingdee/api/form/stk_transferdirect";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(2, $data, $res);
    }

    //推送--调拨赠、借转赠
    public static function pushAllocationZ($allocationObj, $sub)
    {
        //杭州次品仓 调拨单据
        $allocationNumberCPList = WmsRepository::ALLOCATION_CP_NUMBER;
        $stockOrg = ['mz' => '100', 'kz' => '100'];//库存组织
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationObj['allocation_number'])
            ->get(['sku_code as material_no', 'num as qty'])->toArray();
        $isJZS = preg_match("/^JZS/is", $allocationObj['allocation_number']) ? true : false;
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', array_column($allocationOrders, 'material_no'))
            ->get(['product_code', 'selling_price'])->toArray();
        $jyMap = array_column($jyList, 'selling_price', 'product_code');
        foreach ($allocationOrders as &$item){
            $item['stockNo'] = in_array($allocationObj['allocation_number'], $allocationNumberCPList) ? "HZCPC" : "HZC";
            if($isJZS){
                $item['stockNo'] = "DBJ";
            }
            $item['taxprice'] = (Double)$jyMap[$item['material_no']] ?? 0;
        }
        unset($item);
        $data = [
            "billtype_number"=>"XSCKD08_SYS",
            "custom_no"=>"SSYXXD01", // SSYXXD01客户编码
            "stockorg_no"=> '100', //库存组织
            "org_no" => '100',
            "details" => $allocationOrders,
            "id" => 0,
            "billNo" => $allocationObj['allocation_number'],
            "date" => $allocationObj['createtime'],
            "src_dbno" => $isJZS ? $allocationObj['source_allocation_number'] : '',
            "isAutoSubmitAndAudit"=>true
        ];
        $param = [
            "headers" => ["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/sal_outstock";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(1, $data, $res);
    }

    //推送--调拨还
    public static function pushAllocationH($param)
    {
        //杭州次品仓 调拨单据
        $allocationNumberCPList = WmsRepository::ALLOCATION_CP_NUMBER;
        $allocationOrders = [];
        foreach ($param['skudateil'] as $item){
            $allocationOrders[$item['allocation_number']][] = [
                'material_no' => $item['sku_code'],
                'qty' => $item['sj_num']
            ];
        }
        foreach ($allocationOrders as $allocationNumber => $orders){
            $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
            //赠送转归还
            if(preg_match("/^SZH/is", $allocationNumber)){
                return self::pushAllocationSZH($allocationObj, $orders);
            }
            foreach ($orders as &$item) {
                $item['instockno'] = in_array($allocationObj['source_allocation_number'], $allocationNumberCPList) ? 'HZCPC' : 'XTC';
                $item['outstockno'] = 'DBJ';
            }
            unset($item);
            $data = [
                "billtype" => 'ZJDB02_SYS',
                "transferdirecttype" => "InnerOrgTransfer",
                "outstockorgno" => '100',
                "outownerno" => '100',
                "instockorgno" => '100',
                "inownerno" => '100',
                "details" => $orders,
                "id" => 0,
                "billNo" => $allocationObj['allocation_number']."_".date('His'),
                "src_dbno" => $allocationObj['source_allocation_number'],
                "date" => $allocationObj['createtime'],
                "isAutoSubmitAndAudit" => true
            ];
            $param = [
                "headers" =>["Content-Type: application/json; charset=utf-8"],
                "json" => json_encode($data)
            ];
            $url="http://139.224.58.121/kingdee/api/form/stk_transferdirect";
            $res = httpCurl($url, $param);
            return self::pushKingdeeLog(3, $data, $res);
        }
    }

    //推送--调拨送转还
    public static function pushAllocationSZH($allocationObj, $orders)
    {
        //杭州次品仓 调拨单据
        $allocationNumberCPList = WmsRepository::ALLOCATION_CP_NUMBER;
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', array_column($orders, 'material_no'))
            ->get(['product_code', 'selling_price'])->toArray();
        $jyMap = array_column($jyList, 'selling_price', 'product_code');
        foreach ($orders as &$item){
            $item['stockNo'] = in_array($allocationObj['source_allocation_number'], $allocationNumberCPList) ? "HZCPC" : "HZC";
            $item['taxprice'] = (Double)$jyMap[$item['material_no']] ?? 0;
        }
        unset($item);
        $data = [
            "date" => $allocationObj['createtime'],
            "org_no" => '100',
            "billNo" => $allocationObj['allocation_number']."_".date('His'),
            "custom_no"=>"SSYXXD01", // SSYXXD01客户编码 店铺
            "billTypeNo"=>"XSTHD10_SYS",
            "stockorg_no" => "100",
            "details" => $orders,
            "id" => 0,
            "outStockBillNo" => $allocationObj['source_allocation_number'],
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            "headers" => ["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/sal_returnstock";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(3, $data, $res);
    }

    //推送--调拨借转销售
    public static function pushAllocationS($allocationNumber)
    {
        $allocationObj = (new SsyAllocationSaleListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        if(!in_array($allocationObj['is_subject'], ['kz', 'mz'])){
            return ['code' => -1, 'msg' => '仅支持kz、mz类型'];
        }
        $sourceAllocationNumber = unserialize($allocationObj['source_allocation_number']);
        $allocationOrders = (new SsyAllocationSaleTable())->where('allocation_number', $allocationNumber)
            ->get(["sku_code as material_no", "num as qty", "price as taxprice", "createtime"])->toArray();
        $createTime = $allocationOrders[0]['createtime'];
        foreach ($allocationOrders as &$item){
            unset($item['createtime']);
            $item['stockNo'] = "DBJ";
            $item['taxprice'] = (Double)($item['taxprice'] ?: 0);
        }
        unset($item);
        $data = [
            "billtype_number" => "XSCKD01_SYS",
            "custom_no" => "SSYXXD01", // SSYXXD01客户编码
            "org_no" => '100',
            "stockorg_no" => '100',
            "details" => $allocationOrders,
            "id" => 0,
            "billNo" => $allocationNumber,
            "src_dbno" => $sourceAllocationNumber[0],
            "date" => $createTime,
            "isAutoSubmitAndAudit"=>true
        ];
        $param = [
            "headers" => ["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/sal_outstock";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(21, $data, $res);
    }

    //推送--调拨借转内购
    public static function pushAllocationN($allocationNumber)
    {
        $allocationObj = (new SsyAllocationIpurchaseListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        if(!in_array($allocationObj['is_subject'], ['kz', 'mz'])){
            return ['code' => -1, 'msg' => '仅支持kz、mz类型'];
        }
        $allocationOrders = (new SsyAllocationIpurchaseTable())->where('allocation_number', $allocationNumber)
            ->get(["sku_code as material_no", "num as qty", "price as taxprice", "createtime"])->toArray();
        $createTime = $allocationOrders[0]['createtime'];
        foreach ($allocationOrders as &$item){
            unset($item['createtime']);
            $item['stockNo'] = "DBJ";
            $item['taxprice'] = (Double)($item['taxprice'] ?: 0);
        }
        unset($item);
        $data = [
            "billtype_number" => "XSCKD01_SYS",
            "custom_no"=>"SSYKZNG01", // SSYXXD01客户编码 店铺
            "stockorg_no"=> '100', //库存组织
            "org_no" => '100',
            "details" => $allocationOrders,
            "id" => 0,
            "billNo" => $allocationNumber,
            "src_dbno" => $allocationObj['jc_number'],
            "date" => $createTime,
            "isAutoSubmitAndAudit"=>true
        ];
        $param = [
            "headers" => ["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/sal_outstock";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(22, $data, $res);
    }

    //推送供应商  工厂新建成功后调用
    public static function pushFactory($factoryObj)
    {
        $data = [
            "name" => $factoryObj['factory_name'],
            "short_name" => $factoryObj['factory_name_jiancheng'],
            "number" => $factoryObj['supplier_id'],
            "org_no" => "100",
            "id" => 0,
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            "headers" =>["Content-Type: application/json; charset=utf-8"],
            "json" => json_encode($data)
        ];
        $url="http://139.224.58.121/kingdee/api/basic/bd_supplier";
        $jsonRes = httpCurl($url, $param);
        $res = json_decode($jsonRes, true);
        if($res['success']){
            return (new SsyProcessingFactoryNameTable())->updateData($factoryObj['id'], ['kid_id' => $res['id']]);
        }
        return ['code' => -1, 'msg' => $res['msg']??"推送工厂到金蝶失败", 'data' => $res];
    }

    //推送财务应付--绣花
    public static function pushReconciliationXh($id)
    {
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        $reconciliationObj = (new SsyReconciliationOrderTable())->where('id', $id)->first()->toArray();
        if($reconciliationObj['type'] != 1){
            return ["code" => -1, "msg" => "非绣花数据"];
        }
        if(!isset($brandOrg[$reconciliationObj['source_factory_groups_id']])){
            return ['code' => -1, 'msg' => '组织编码不存在!'];
        }
        $purchaseinIds = array_map(function ($item){return (Int)$item;}, unserialize($reconciliationObj['purchasein_ids']));
        $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $purchaseinIds)->orderBy('id', 'asc')
            ->get(["processing_code","type_no","r_years","pay_machining_price"])->toArray();
        $details = [];
        foreach ($returnList as $item){
            $firstDay = date('Y-m-01 00:00:00', strtotime($item['r_years']));
            $lastDay = date("Y-m-t 23:59:59", strtotime($item['r_years']));
            $returns = (new SsyJstPurchaseinOrderTable())->where('processing_code', $item['processing_code'])->whereBetween('ke_date', [$firstDay, $lastDay])
                ->get(["sku_id", "qty"])->toArray();
            $detail = [];
            foreach ($returns as $return){
                if(isset($detail[$return['sku_id']])){
                    $detail[$return['sku_id']]['qty'] += $return['qty'];
                }else{
                    $detail[$return['sku_id']] = [
                        'expenseItemNo' => 'FYXM18_SYS',
                        'processNo' => $item['processing_code'],
                        'taxPrice' => $item['pay_machining_price'], //暂估价 传大货价
                        'material_no' => $return['sku_id'],
                        'qty' => $return['qty']
                    ];
                }
            }
            $detail = array_values($detail);
            $details = array_merge($details, $detail);
        }
        $data = [
            "billType" => "YFD02_SYS",
            "settlementOrg" => $brandOrg[$reconciliationObj['source_factory_groups_id']],
            "accountType" => 3, //2暂估应付 、3财务应付
            "supplierNo" => $reconciliationObj['supplier_id'], //供应商编码
            "details" => $details,
            "id" => 0,
            "billNo" => $reconciliationObj['renumber'],
            "date" => date('Y-m-d H:i:s'),
            "businessType" => "FY",
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/peappushfinanceap"; //财务应付
        $res = httpCurl($url, $param);
        $pushRes = self::pushKingdeeLog(5, $data, $res);
        if($pushRes['code'] === 0){
            (new SsyReconciliationOrderTable())->updateData($id, ['is_push' => 1]);
        }
        return $pushRes;
    }

    //推送财务应付--成衣
    public static function pushReconciliationCy($id)
    {
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        $reconciliationObj = (new SsyReconciliationOrderTable())->where('id', $id)->first()->toArray();
        if($reconciliationObj['type'] != 0){
            return ["code" => -1, "msg" => "非成衣数据"];
        }
        if(!isset($brandOrg[$reconciliationObj['source_factory_groups_id']])){
            return ['code' => -1, 'msg' => '组织编码不存在!'];
        }
        $purchaseinIds = array_map(function ($item){return (Int)$item;}, unserialize($reconciliationObj['purchasein_ids']));
        $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $purchaseinIds)->orderBy('id', 'asc')
            ->get(["processing_code","type_no","r_years","pay_price"])->toArray();
        $details = [];
        foreach ($returnList as $item){
            $firstDay = date('Y-m-01 00:00:00', strtotime($item['r_years']));
            $lastDay = date("Y-m-t 23:59:59", strtotime($item['r_years']));
            $skuList = (new SsyJstPurchaseinOrderTable())->where('processing_code', $item['processing_code'])->whereBetween('ke_date', [$firstDay, $lastDay])
                ->groupBy("sku_id")->get(["sku_id"])->toArray();
            foreach ($skuList as $skuObj){
                //如果有返修要拼上负数
                $repairObj = (new SsyPurchaseReturnTable())->where('processing_code', $item['processing_code'])->where('sku_code', $skuObj['sku_id'])
                    ->where('groups', 1)->first();
                $repairObj = !empty($repairObj) ? $repairObj->toArray() : [];
                $sum = (new SsyJstPurchaseinOrderTable())->where('processing_code', $item['processing_code'])->where('sku_id', $skuObj['sku_id'])
                    ->whereBetween('ke_date', [$firstDay, $lastDay])->sum('qty');
                $details[] = [
                    'expenseItemNo' => 'FYXM18_SYS',
                    'processNo' => $item['processing_code'],
                    'taxPrice' => $item['pay_price'],
                    'material_no' => $skuObj['sku_id'],
                    'qty' => isset($repairObj['sj_num']) ? (Int)$sum-$repairObj['sj_num'] : (Int)$sum
                ];
            }
        }
        $data = [
            "billType" => "YFD01_SYS",
            "settlementOrg" => $brandOrg[$reconciliationObj['source_factory_groups_id']] ?? "",
            "accountType" => 3,
            "supplierNo" => $reconciliationObj['supplier_id'],
            "details" => $details,
            "id" => 0,
            "billNo" => $reconciliationObj['renumber'],
            "date" => date('Y-m-d H:i:s'),
            "businessType" => "FY",
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url="http://139.224.58.121/kingdee/api/form/stappushfinanceap2";
        $res = httpCurl($url, $param);
        $pushRes = self::pushKingdeeLog(6, $data, $res);
        if($pushRes['code'] === 0){
            (new SsyReconciliationOrderTable())->updateData($id, ['is_push' => 1]);
        }
        return $pushRes;
    }

    //推送财务应付--违约罚款--成衣
    public static function pushReconciliationFine($id)
    {
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        $reconciliationObj = (new SsyReconciliationOrderTable())->where('id', $id)->first()->toArray();
        if($reconciliationObj['type'] != 0){
            return ['code' => -1, 'msg' => "非成衣对账单"];
        }
        if(empty($reconciliationObj['fine_ids'])){
            return ['code' => -1, 'msg' => "没有成衣罚单"];
        }
        $pushLog = (new SsyPushKingdeeLogTable())->where('bill_no', 'F_'.$reconciliationObj['renumber'])->first(['kid_id']);
        if($pushLog->kid_id ?? ""){
            return ['code' => 0, 'msg' => '成衣罚单已推送, 无需推送'];
        }
        $fineIds = array_map(function ($item){return (Int)$item;}, unserialize($reconciliationObj['fine_ids']));
        $fineList = (new SsyFineAmountTable())->whereIn('id', $fineIds)->get(["processing_code","type_no","amount"])->toArray();
        if(empty($fineList)){
            return ['code' => -1, 'msg' => '未找到罚款单号: '.json_encode($fineIds)];
        }
        $details = [];
        $processingList = (new SsyProcessingListTable())->whereIn('processing_code', array_column($fineList, "processing_code"))
            ->get(["type_no","sku_code"])->toArray();
        $skuMap = array_column($processingList, 'sku_code', 'type_no');
        foreach ($fineList as $item){
            $detail = [
                'expenseItemNo' => 'FYXM18_SYS',
                'qty' => -1,
                'processNo' => $item['processing_code'],
                'taxPrice' => $item['amount'],
                'material_no' => $skuMap[$item['type_no']]
            ];
            $details[] = $detail;
        }
        $data = [
            "billType" => "YFD05_SYS",
            "settlementOrg" => $brandOrg[$reconciliationObj['source_factory_groups_id']] ?? "",
            "accountType" => 3,
            "supplierNo" => $reconciliationObj['supplier_id'],
            "details" => $details,
            "id" => 0,
            "billNo" => 'F_'.$reconciliationObj['renumber'],
            "date" => date('Y-m-d H:i:s'),
            'businessType' => 'CG',
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url="http://139.224.58.121/kingdee/api/form/ap_payable";
        $res = httpCurl($url, $param);
        $pushRes = self::pushKingdeeLog(7, $data, $res);
        if($pushRes['code'] === 0){
            (new SsyReconciliationOrderTable())->updateData($id, ['is_fine_push' => 1]);
        }
        return $pushRes;
    }

    //推送财务应付--额外费用--成衣
    public static function pushReconciliationExtra($id)
    {
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        $reconciliationObj = (new SsyReconciliationOrderTable())->where('id', $id)->first()->toArray();
        if($reconciliationObj['type'] != 0){
            return ['code' => -1, 'msg' => "非成衣对账单"];
        }
        if(empty($reconciliationObj['additional_ids'])){
            return ['code' => -1, 'msg' => "没有额外费用"];
        }
        $pushLog = (new SsyPushKingdeeLogTable())->where('bill_no', 'E_'.$reconciliationObj['renumber'])->first(['kid_id']);
        if($pushLog->kid_id ?? ""){
            return ['code' => 0, 'msg' => '额外费用已推送, 无需重复推送'];
        }
        $additionalIds = array_map(function ($item){return (Int)$item;}, unserialize($reconciliationObj['additional_ids']));
        $additionalList = (new SsyAdditionalAmountTable())->whereIn('id', $additionalIds)->get(["processing_code","type_no","amount"])->toArray();
        if(empty($additionalList)){
            return ['code' => -1, 'msg' => '未找到额外费用单号: '.json_encode($additionalIds)];
        }
        $details = [];
        $processingList = (new SsyProcessingListTable())->whereIn('processing_code', array_column($additionalList, "processing_code"))
            ->get(["type_no","sku_code"])->toArray();
        $skuMap = array_column($processingList, 'sku_code', 'type_no');
        foreach ($additionalList as $item){
            $detail = [
                'expenseItemNo' => 'FYXM18_SYS',
                'qty' => -1,
                'processNo' => $item['processing_code'],
                'taxPrice' => $item['amount'],
                'material_no' => $skuMap[$item['type_no']]
            ];
            $details[] = $detail;
        }
        $data = [
            "billType" => "YFD06_SYS",
            "settlementOrg" => $brandOrg[$reconciliationObj['source_factory_groups_id']] ?? "",
            "accountType" => 3,
            "supplierNo" => $reconciliationObj['supplier_id'],
            "details" => $details,
            "id" => 0,
            "billNo" => 'E_'.$reconciliationObj['renumber'],
            "date" => date('Y-m-d H:i:s'),
            'businessType' => 'CG',
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url="http://139.224.58.121/kingdee/api/form/ap_payable";
        $res = httpCurl($url, $param);
        $pushRes = self::pushKingdeeLog(71, $data, $res);
        if($pushRes['code'] === 0){
            (new SsyReconciliationOrderTable())->updateData($id, ['is_extra_push' => 1]);
        }
        return $pushRes;
    }

    //推送返修对账单
    public static function pushReconciliationRepair($id)
    {
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        $repairObj = (new SsyRepairReconciliationOrderTable())->where('id', $id)->first()->toArray();
        $billNos = [
            ['type' => '+', 'bill_no' => $repairObj['renumber']],
            ['type' => '-', 'bill_no' => "R_".$repairObj['renumber']]
        ];
        $isPush = false;
        foreach ($billNos as $item){
            $billNo = $item['bill_no'];
            $pushLog = (new SsyPushKingdeeLogTable())->where('bill_no', $billNo)->first(['kid_id']);
            if($pushLog->kid_id ?? ""){
               continue;
            }
            $type = 9;
            $data= [];
            //正数 回货统计单
            if($item['type'] == '+'){
                $ids = unserialize($repairObj['purchasein_ids']);
                if(!empty($ids)){
                    $returnList = (new SsyJstPurchaseinOrderEmbroideryCountTable())->whereIn('id', $ids)->orderBy('id', 'asc')
                        ->get(["processing_code", "totalnum", "cost_amount", "type_no"])->toArray();
                    $processingList = (new SsyProcessingListTable())->whereIn('processing_code', array_column($returnList, "processing_code"))
                        ->get(["type_no","sku_code"])->toArray();
                    $skuMap = array_column($processingList, 'sku_code', 'type_no');
                    $details = [];
                    foreach ($returnList as $rItem){
                        $details[] = [
                            'expenseItemNo' => 'FYXM18_SYS',
                            'qty' => $rItem['totalnum'],
                            'processNo' => $rItem['processing_code'],
                            'taxPrice' => $rItem['cost_amount'],
                            'material_no' => $skuMap[$rItem['type_no']]
                        ];
                    }
                    $data = [
                        "billType" => "YFD07_SYS",
                        "settlementOrg" => $brandOrg[$repairObj['source_factory_groups_id']] ?? "",
                        "accountType" => 3,
                        "supplierNo" => $repairObj['supplier_id'],
                        "details" => $details,
                        "id" => 0,
                        "billNo" => $billNo,
                        "date" => date('Y-m-d H:i:s'),
                        'businessType' => 'CG',
                        "isAutoSubmitAndAudit" => true
                    ];
                }
            }
            //负数 返修退款
            if($item['type'] == '-'){
                $type = 91;
                $repairIds = unserialize($repairObj['repair_ids']);
                if(!empty($repairIds)){
                    $repairList = (new SsyRepairAmountTable())->whereIn('id', $repairIds)->orderBy('id', 'asc')
                        ->get(["processing_code", "type_no", "num", "amount"])->toArray();
                    $processingList = (new SsyProcessingListTable())->whereIn('processing_code', array_column($repairList, "processing_code"))
                        ->get(["type_no","sku_code"])->toArray();
                    $skuMap = array_column($processingList, 'sku_code', 'type_no');
                    $details = [];
                    foreach ($repairList as $rItem){
                        $details[] = [
                            'expenseItemNo' => 'FYXM18_SYS',
                            'qty' => -$rItem['num'],
                            'processNo' => $rItem['processing_code'],
                            'taxPrice' => $rItem['amount'],
                            'material_no' => $skuMap[$rItem['type_no']]
                        ];
                    }
                    $data = [
                        "billType" => "YFD07_SYS",
                        "settlementOrg" => $brandOrg[$repairObj['source_factory_groups_id']] ?? "",
                        "accountType" => 3,
                        "supplierNo" => $repairObj['supplier_id'],
                        "details" => $details,
                        "id" => 0,
                        "billNo" => $billNo,
                        "date" => date('Y-m-d H:i:s'),
                        'businessType' => 'CG',
                        "isAutoSubmitAndAudit" => true
                    ];
                }
            }
            if(!empty($data)){
                $isPush = true;
                $param = [
                    'headers' => ["Content-Type: application/json; charset=utf-8"],
                    'json' => json_encode($data)
                ];
                $url="http://139.224.58.121/kingdee/api/form/ap_payable";
                $res = httpCurl($url, $param);
                $pushRes = self::pushKingdeeLog($type, $data, $res);
                if($pushRes['code'] !== 0){
                    return $pushRes;
                }
            }
        }
        if($isPush){
            return (new SsyRepairReconciliationOrderTable())->updateData($id, ['is_push' => 1]);
        }else{
            return ['code' => -1, 'msg' => '没有可以推送的数据'];
        }
    }

    //推送暂估应付--绣花
    public static function pushReconciliationXhZg($id)
    {
        $orderObj = (new SsyReconciliationOrderZgTable())->where('id', $id)->first()->toArray();
        $brandOrg = [
            "3090235" => "100", //SSY十三余
            "10010" => "102"    //YXRG有香如故
        ];
        if(!isset($brandOrg[$orderObj['source_factory_groups_id']])){
            return ['code' => -1, 'msg' => '组织编码不存在!'];
        }
        $data = [
            "billType" => "YFD02_SYS",
            "settlementOrg" => $brandOrg[$orderObj['source_factory_groups_id']],
            "accountType" => 2, //2暂估应付 、3财务应付
            "supplierNo" => $orderObj['supplier_id'], //供应商编码
            "details" => [],
            "id" => 0,
            "billNo" => $orderObj['renumber'],
            "date" => date('Y-m-t 00:00:00', strtotime($orderObj['recon_time'])),
            "businessType" => "FY",
            "isAutoSubmitAndAudit" => true
        ];
        $detail = json_decode($orderObj['detail'], true);
        foreach ($detail as $item){
            $data['details'][] = [
                'expenseItemNo' => 'FYXM18_SYS',
                'processNo' => $item['processing_code'],
                'taxPrice' => $item['contract_machining_price'], //暂估价 传大货价
                'material_no' => $item['sku_code'],
                'qty' => $item['qty']
            ];
        }
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/ap_payable";//暂估应付
        $res = httpCurl($url, $param);
        $pushRes = self::pushKingdeeLog(4, $data, $res);
        if($pushRes['code'] === 0){
            (new SsyReconciliationOrderZgTable())->updateData($id, ['is_push' => 1]);
        }
        return $pushRes;
    }

    //对账单信息--付款后(成衣、绣花)
    public static function pushReconciliationPay($id)
    {
        $brandOrg = [
            "3090235" => ["org" => "100", "account" => "33220188000118026"], //SSY十三余
            "10010" => ["org" => "102", "account" => "201000345686371"]    //YXRG有香如故
        ];
        $reconciliationObj = (new SsyReconciliationOrderTable())->where('id', $id)->first()->toArray();
        $detail[]= [
            "amount"=> $reconciliationObj['pay_amount'],
            "remark"=>'',
            "account" => $brandOrg[$reconciliationObj['source_factory_groups_id']]['account'],
            "expenseItem"=>'',
            "settlementMethod"=>"JSFS04_SYS",
            "paymentPurpose"=>'SFKYT08_SYS',
        ];
        $data = [
            "billType" => "FKDLX01_SYS",
            "expectedPaymentDate" => date('Y-m-d H:i:s'),// 期望付款日期
            "supplierNo" => $reconciliationObj['supplier_id'],
            "settleOrgNo" => $brandOrg[$reconciliationObj['source_factory_groups_id']]['org'],//组织
            "departmentNo" => "",//部门
            "details" => $detail,
            "id" => 0,
            "billNo" => $reconciliationObj['renumber'],
            "date" => $reconciliationObj['createtime'],
            "account" => "",
            "isAutoSubmitAndAudit" => true
        ];
        $param = [
            'headers' => ["Content-Type: application/json; charset=utf-8"],
            'json' => json_encode($data)
        ];
        $url = "http://139.224.58.121/kingdee/api/form/ap_paybill";
        $res = httpCurl($url, $param);
        return self::pushKingdeeLog(8, $data, $res);
    }

    //保存推送金蝶的推送日志
    public static function pushKingdeeLog($type, $param, $resp)
    {
        $res = json_decode($resp, true);
        $kidId = $res['success'] ? $res['id'] : "";
        $saveData = [
            "bill_no" => $param['billNo'],
            "kid_id" => $kidId,
            "data" => json_encode($param, JSON_UNESCAPED_UNICODE),
            "error" => $resp,
            "type" => $type, //1赠、2借、21借转销售、22借转内购、3还、4绣花暂估、5绣花应付、6成衣应付、7成衣罚款、71成衣额外费用、8绣花\成衣对账、9采退返修对账单-正数、91采退返修对账单-负数
            "create_time" => date('Y-m-d H:i:s')
        ];
        $whereParam = ['bill_no' => $param['billNo'], 'type' => $type];
        $logObj = (new SsyPushKingdeeLogTable())->where($whereParam)->first();
        if(!empty($logObj)){
            unset($saveData['create_time']);
            (new SsyPushKingdeeLogTable())->updateDataWhere($whereParam, $saveData);
        }else{
            (new SsyPushKingdeeLogTable())->createData($saveData);
        }
        return !empty($kidId) ? ['code' => 0, 'msg' => '推送成功'] : ['code' => -1, 'msg' => '推送失败: '.$resp, 'data' => $res];
    }
}
